/*
 * SPI3_UNIT.c
 *
 *  Created on: Nov 5, 2021
 *      Author: ITry
 */

#include <SoftSPI3.h>
#include <SPI3_UNIT.h>

/*
 *  sclk = PC8;
	cs = PC1;
	mosi = miso =PC5;
 */

int spi3_read_byte (void* bus_param, uint8_t dev_addr, uint8_t reg_addr, uint8_t *data){
/*uint8_t value;
  ClrSoftSPICS();//CS片选拉低
  SPI_Write_OneByte(0x80);//SPI写地址命令
  SPI_Write_OneByte(reg_addr);
  value = SPI_Read_OneByte();//SPI读数据
  SetSoftSPICS();//CS片选拉高
  return value;*/
	return spi3_read_bytes(bus_param, dev_addr, reg_addr, 1, data);
}

int spi3_read_bytes (void* bus_param, uint8_t dev_addr, uint8_t reg_addr, uint8_t len, uint8_t *data){
	ClrSoftSPI3CS();//CS片选拉低
	if (len == 1)
	{
		SPI3_Write_OneByte(0x80);//SPI写地址命令
	}
	else if (len == 2)
	{
		SPI3_Write_OneByte(0xA0);//SPI写地址命令
	}
	else if (len == 3)
	{
		SPI3_Write_OneByte(0xC0);//SPI写地址命令
	}
	else
	{
		SPI3_Write_OneByte(0xE0);//SPI写地址命令
	}
	SPI3_Write_OneByte(reg_addr);
	for (uint8_t i = 0; i < len; i++)
	{
	  data[i] = SPI3_Read_OneByte();//SPI读数据
	}
	SetSoftSPI3CS();//CS片选拉高
	return 0;
}

int spi3_write_byte (void* bus_param, uint8_t dev_addr, uint8_t reg_addr, uint8_t data){
	ClrSoftSPI3CS();//CS片选拉低
	SPI3_Write_OneByte(0x00);//SPI写地址命令
	SPI3_Write_OneByte(reg_addr);
	SPI3_Write_OneByte(data);//SPI写数据
	SetSoftSPI3CS();//CS片选拉高
	return 0;
}
